package com.xy.wsl.api.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class SecretUtil {
    public static String md5(String originalString) {
        try {
// 创建MessageDigest对象并指定算法为MD5
            MessageDigest md = MessageDigest.getInstance("MD5");

// 将原始字符串转换为字节数组
            byte[] originalBytes = originalString.getBytes();

// 使用MessageDigest对象更新字节数组
            md.update(originalBytes);

// 执行哈希计算并获取结果字节数组
            byte[] resultBytes = md.digest();

// 将字节数组转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : resultBytes) {
                sb.append(String.format("%02x", b));
            }

            String encryptedString = sb.toString();

            return encryptedString;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encrypt_aes(String plainText, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt_aes(String encryptedText, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }
}
